package com.lss.music.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.lss.music.R;
import com.lss.music.utils.PermissionHelper;

/**
 * 应用启动页
 */
@SuppressLint("CustomSplashScreen")
public class SplashActivity extends AppCompatActivity {
    private PermissionHelper permissionHelper;
    private TextView tvSkip;
    private CountDownTimer countDownTimer;
    private static final long SPLASH_DELAY = 2850; // 3秒
    private static final long COUNTDOWN_INTERVAL = 1000; // 1秒更新一次
    private static final long COUNTDOWN_TOTAL = 3000; // 总倒计时3秒
    private boolean isActivityFinished = false; // 添加标志位防止多次跳转
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_splash);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // 初始化跳过按钮
        tvSkip = findViewById(R.id.tv_skip);
        tvSkip.setOnClickListener(v -> skipSplash());

        // 启动倒计时
        startCountDown();

        // 初始化权限助手
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissionHelper = new PermissionHelper(this);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissionHelper.setOnApplyPermissionListener(() -> {
                // 所有权限已获取，进入主界面
                enterMainActivity();
            });
        }

        // 检查并申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (permissionHelper.isAllRequestedPermissionGranted()) {
                enterMainActivity();
            } else {
                permissionHelper.applyPermissions();
            }
        }
    }

    /**
     * 启动倒计时
     */
    private void startCountDown() {
        countDownTimer = new CountDownTimer(COUNTDOWN_TOTAL, COUNTDOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新跳过按钮文本
                int seconds = (int) (millisUntilFinished / 1000);
                tvSkip.setText(getString(R.string.skip, seconds));
            }

            @Override
            public void onFinish() {
                // 倒计时结束，自动跳过
                skipSplash();
            }
        }.start();
    }

    /**
     * 跳过启动页
     */
    private void skipSplash() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        enterMainActivity();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissionHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 进入主界面
     */
    private void enterMainActivity() {
        // 防止多次跳转
        if (isActivityFinished) {
            return;
        }
        isActivityFinished = true;
        // 使用Handler延迟进入主界面，确保动画效果
        new Handler().postDelayed(() -> {
            startActivity(new Intent(SplashActivity.this, HomeActivity.class));
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }, SPLASH_DELAY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}